<?php
declare (strict_types=1);

namespace app\listener;

use app\common\job\TradeExpiration;
use app\common\model\Trade;
use app\common\service\GatewayClientServer;
use think\facade\Queue;

class TradeCreated
{

    /**
     * 订单创建
     * @param Trade $trade
     * @return void
     */
    public function handle(Trade $trade)
    {
        $payExpTime = $trade->payExpTime ?: null;
        if (is_numeric($payExpTime)) {
            $time = $payExpTime - time() + 1;
            if ($time > 0) {
                $job_data = ['id' => $trade->id];
                Queue::later($time, TradeExpiration::class, $job_data);
            }
        }

        // 订单创建后，更新红点
        $data = [
            'action' => REDDOT,
            'data' => [],
        ];
        $this->getGatewayClientServer()->sendToUid($trade->memberId, json_encode($data));
    }

    private function getGatewayClientServer(): GatewayClientServer
    {
        return app(GatewayClientServer::class);
    }
}
